import { getFromStorage, saveToStorage } from "../storage.js"

const CN_KEY_PREFIX = "cn_calendar_year"
const TTL = 1000 * 60 * 60 * 24 * 7 // 1 week

// Source: Timor 假期接口 (含节假日与补班)
// https://timor.tech/api/holiday/year/{year}
async function fetchCnYear(year) {
  const res = await fetch(`https://timor.tech/api/holiday/year/${year}`)
  const json = await res.json()
  if (!res.ok || json?.code !== 0)
    throw new Error("Failed to fetch CN holidays")
  const holidayObj = json.holiday || {}
  const holidays = []
  const workdays = []
  for (const key of Object.keys(holidayObj)) {
    const info = holidayObj[key]
    // info.date 是 YYYY-MM-DD；holiday=true 为放假，false 为补班（工作日）
    if (info?.holiday === true) holidays.push(info.date)
    if (info?.holiday === false) workdays.push(info.date)
  }
  const payload = { year, holidays, workdays, ts: Date.now() }
  await saveToStorage(`${CN_KEY_PREFIX}_${year}`, payload)
  return payload
}

export async function getCnCalendar(year) {
  const cached = await getFromStorage(`${CN_KEY_PREFIX}_${year}`)
  if (cached && Date.now() - (cached.ts || 0) < TTL) return cached
  return fetchCnYear(year)
}

// Backward shim for old callers (if any)
export async function getHolidays() {
  const y = new Date().getFullYear()
  return getCnCalendar(y)
}

export async function scheduleHolidayRefresh(force = false) {
  const y = new Date().getFullYear()
  const cached = await getFromStorage(`${CN_KEY_PREFIX}_${y}`)
  if (force || !cached || Date.now() - (cached.ts || 0) >= TTL) {
    try {
      await fetchCnYear(y)
    } catch (_e) {}
  }
}
